import router from './index'

// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'

import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  // NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      // NProgress.done()
    } else {
      next()
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      let nextPath = `/login?redirect=${to.path}`
      for (const key in to.query) {
        nextPath += `&${key}=${to.query[key]}`
      }
      next(nextPath)
      // NProgress.done()
    }
  }
})

router.afterEach(() => {
  // NProgress.done()
})
